/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.garagesale.user.web.action;

import com.garagesale.data.DBAccess;
import com.garagesale.data.Item;
import com.garagesale.data.ItemCategory;
import com.garagesale.data.User;
import com.garagesale.web.form.ItemForm;
import com.garagesale.web.util.WebAction;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

/**
 *
 * @author christophe
 */
public class SaveItemAction extends org.apache.struts.action.Action
{

    /* forward name="success" path="" */
    private static final String SUCCESS = "view";

    /**
     * This is the action called from the Struts framework.
     * @param mapping The ActionMapping used to select this instance.
     * @param form The optional ActionForm bean for this request.
     * @param request The HTTP Request we are processing.
     * @param response The HTTP Response we are processing.
     * @throws java.lang.Exception
     * @return
     */
    @Override
    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception
    {

        ItemForm itemForm = (ItemForm) form;

        Item item = itemForm.toItem();



        // delete the item
        if (WebAction.DELETE.isAction(itemForm.getAction()))
        {
            // TODO: perform check to make sure the user can actually delete this item
            Item toDelete = DBAccess.getInstance().retrieveByID(Item.class, item.getItemID());
            DBAccess.getInstance().delete(toDelete);
            return new ActionForward("/user/viewUser.do");
        }



        // make sure that the item is complete
        item.setItemCategory(new ItemCategory());
        item.getItemCategory().setItemCategoryID(itemForm.getItemCategoryID());

        User user = (User) request.getSession().getAttribute("user");
        item.setUserBySellerUserId(user);

        Date today = new Date();

        item.setCreatedDate(today);

        Integer createdID = DBAccess.getInstance().create(item);



        return new ActionForward("/user/viewItem.do?itemID=" + createdID + "&created=true", true);

    }
}
